import os
import requests
from multiprocessing import Pool
from urllib.parse import urljoin

# ESRI 瓦片服务的 URL 模板
TILE_URL_TEMPLATE = "https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}"

# 下载瓦片的函数
def download_tile(args):
    z, y, x, save_dir = args
    url = TILE_URL_TEMPLATE.format(z=z, y=y, x=x)
    try:
        # 获取瓦片图像数据
        response = requests.get(url, timeout=10)
        if response.status_code == 200:
            # 构造文件路径
            tile_filename = f"{x}.png"
            tile_path = os.path.join(save_dir, tile_filename)

            # 将瓦片图像保存到本地文件
            with open(tile_path, 'wb') as file:
                file.write(response.content)
            print(f"下载成功: {tile_filename}")
        else:
            print(f"请求失败: {url}, 状态码: {response.status_code}")
    except Exception as e:
        print(f"下载出错: {url}, 错误: {e}")

# 创建目录
def create_directory(save_dir):
    if not os.path.exists(save_dir):
        os.makedirs(save_dir)

# 批量下载瓦片
def download_tiles(zoom, y_range, x_range, save_dir, num_workers=4):
    # create_directory(save_dir)
    
    # 准备要下载的瓦片任务

    print()
    tasks = [(zoom, y, x, save_dir) for y in y_range for x in x_range]
    print(tasks)


    # # 使用进程池来并行下载
    with Pool(processes=num_workers) as pool:
        pool.map(download_tile, tasks)

if __name__ == "__main__":
    # 设置瓦片的 Z、Y、X 范围
    z = 16
    y_range = range(0, 80)  # 设置 Y 范围
    x_range = range(0, 80)  # 设置 X 范围
    
    # 保存瓦片的目录
    save_dir = "tiles"

    # 执行下载任务
    download_tiles(z, y_range, x_range, save_dir, num_workers=4)
